package com.frogs.ucenter.v1.interceptor;



import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.v1.service.UserAccountInfoService;
/**
 * 接口调用验证
 * @author wushubin
 *
 */
public class VisitInterceptor extends BaseInterceptor {
	private static final Logger log = LoggerFactory.getLogger(VisitInterceptor.class);
	
	@Resource
	private UserAccountInfoService userAccountInfoService;
	
	@Resource
	private RequestApiHelper requestApiHelper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String url = request.getRequestURL().toString();
		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
		
		log.info("func[preHandle] url[{}] params[{}] ip[{}]", new Object[] {url,getRequestParams(request) , reqInfo.getUserIp()});
		
		String appId = request.getParameter(ApiUrlParamEnum.appId.getParamName());
		String openKey = request.getParameter(ApiUrlParamEnum.openKey.getParamName());
		String userIp = reqInfo.getUserIp();
		String verifyCode = reqInfo.getParameter(ApiUrlParamEnum.verify.getParamName(), "");
		Integer userId = reqInfo.getIntParameter(ApiUrlParamEnum.userId.getParamName(), 0);
		String tip = "error request";
		try {
			// 授权系统访问 跳过
			if (!StringUtil.isEmpty(openKey)) {
				if(openKey.equals(StringUtil.md5("ucenter"+"ucenter_20150211", "open.com"))) {
					return true;
				} else {
					tip = "error key";
					throw new ServiceOperationException(tip);
				}
			}
			JSONObject result = requestApiHelper.verifyPermission(url, appId, userIp, userId, verifyCode);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				Integer isVisit = result.getJSONObject("response").getIntValue("isVisit");
				if (isVisit == 0) {
					tip = result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName());
					throw new ServiceOperationException(tip);
				}
			} else {
				tip = "This interface url no permissions!";
				throw new ServiceOperationException("该账号没有这个接口的访问权限！");
			}
		} catch (ServiceOperationException e) {
			log.error("func[preHandle] url[{}] params[{}] error[{}-{}]", new Object[] {url,getRequestParams(request) , e.getMessage() , e});
			response.getWriter().write(this.getExceptionResult(request, tip));
			response.flushBuffer();  
			return false;
		}
		return true;
	}
	
	private String getExceptionResult(HttpServletRequest request, String tip){
		String url = request.getRequestURL().toString();
		String callback = request.getParameter(ApiUrlParamEnum.callback.getParamName());
		
		String result = "";
		if(url.indexOf(".json") > 0 ){
			if(StringUtil.isEmpty(callback)){
				result = "{\"response\": {\"code\": 0,\"tip\": \""+tip+"\"}}";
			}else{
				result = callback+"({\"response\": {\"code\": 0,\"tip\": \""+tip+"\"}})";
			}
		} else{
			result = "error request";
		}
		return result;
	}

}

